package com.lantosec.hmrp.modules.sysdata.service.impl;

import com.lantosec.hmrp.core.util.DateUtils;
import com.lantosec.hmrp.modules.sysdata.entity.SysDataSerialNumber;
import com.lantosec.hmrp.modules.sysdata.mapper.SysDataSerialNumberMapper;
import com.lantosec.hmrp.modules.sysdata.service.ISysDataSerialNumberService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.context.annotation.Primary;
import lombok.extern.log4j.Log4j2;
import org.springframework.transaction.annotation.Transactional;

import java.text.DecimalFormat;
import java.util.Date;
import java.util.Objects;

/**
 * <p>
 * 流水号规则表 服务实现类
 * </p>
 *
 * @author AutoCode
 * @since 2020-06-22
 */
@Service
@Primary
@Log4j2
public class SysDataSerialNumberServiceImpl extends ServiceImpl<SysDataSerialNumberMapper, SysDataSerialNumber> implements ISysDataSerialNumberService {

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String generateSerialNumber(String id) {
        SysDataSerialNumber serialNumber = baseMapper.selectById(id);
        if (Objects.isNull(serialNumber)) {
            return "";
        }
        String rules = serialNumber.getSerialRules();
        String before = rules.substring(0, rules.indexOf("#"));
        String data = "";
        if (StringUtils.isNotEmpty(before)) {
            data = DateUtils.currDateFormat(before);
        }
        // 当前值
        Integer currentValue = serialNumber.getCurrentNumber();
        if (currentValue == 0) {
            currentValue = serialNumber.getStartValue();
        } else {
            currentValue = currentValue + serialNumber.getIncrement();
        }
        String after = rules.substring(rules.indexOf("#"));
        // 补0
        DecimalFormat g1 = new DecimalFormat(after.replace("#","0"));
        String numberStr = g1.format(currentValue);

        String code = data + numberStr;

        // 更新当前值
        serialNumber.setCurrentNumber(currentValue);
        serialNumber.setUpdateTime(new Date());
        baseMapper.updateById(serialNumber);

        return code;
    }
}
